﻿#region Copyright (c) 2012-11, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Runtime.Serialization;
using System.Threading;
using Amarok.Agents.Resources;


namespace Amarok.Agents
{
	/// <summary>
	/// This type represents an Operation Message. Operation Messages are a special kind of Message intended to 
	/// trigger the execution of operations. That can be either operations for changing state, for example starting 
	/// a measurement, or operations for querying information, for example querying the list of users.
	/// 
	/// Types derived from this base class should follow a naming convention. An Operation Message intended to change 
	/// state or data should be named after the object that is affected, preceded by a verb that describes how that 
	/// object is affected; for example: StartMeasurement, AddUser, ExitApplication. An Operation Message intended to 
	/// query information should be named after the object which is queried, preceded by the verb Query; for example: 
	/// QueryUsers, QueryMeasurementStatus.
	/// 
	/// As for all Messages, it is good design practice to implement Operation Messages as immutable types so that 
	/// accidental modifications are impossible. This is important since Operation Messages will be transfered to 
	/// other Agents, thus, it is very likely that the content of those Operation Messages will be accessed in other 
	/// threads concurrently.
	/// 
	/// In addition, Operation Messages should contain copies of data (entities) or some kind of unique identifier 
	/// (identities). Latter can then be used to query for that identified entities. Never transfer object references 
	/// to private Agent data, except for global shared data that never changes; always transfer copies of data.
	/// </summary>
	[Serializable]
	public abstract class Operation : Message,
		IDisposable
	{
		// Implementation Notes:
		//
		//	Some fields are marked as non-serialized, because we don't want their state to be transfered
		//	between processes. This causes those fields not being initialized on deserialization, so we have 
		//	to initialize them manually by implementing a custom deserialization callback.

		// data
		[NonSerialized]
		private CancellationTokenSource mCancellationTokenSource;
		[NonSerialized]
		private Int32 mAcquireCount;


		#region ++ IDisposable Interface ++

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		void IDisposable.Dispose()
		{
			OnDispose();
		}

		#endregion

		#region ++ Public Interface (Acquire) ++

		/// <summary>
		/// Acquires the Operation Message for further processing. If this is the first call, then the method 
		/// returns immediately. Any subsequent calls will throw an appropriate exception, indicating that the 
		/// Operation Message has been acquired before.
		/// 
		/// This method is used by Operation Message Handler to ensure that only one handler is processing the
		/// Operation Message.
		/// </summary>
		/// 
		/// <exception cref="InvalidOperationException">
		/// The Operation Message has already been acquired.</exception>
		public void Acquire()
		{
			if (Interlocked.Increment(ref mAcquireCount) > 1)
				throw new InvalidOperationException(AgentResources.OperationAlreadyAcquired);
		}

		/// <summary>
		/// Tries to acquire the Operation Message for further processing. If this is the first call, then the 
		/// method returns true. Any subsequent calls will return false, notifying that the Operation Message has 
		/// been acquired before.
		/// 
		/// This method is used by Operation Message Handler to ensure that only one handler is processing the
		/// Operation Message.
		/// </summary>
		/// 
		/// <returns>
		/// True to indicate that the Operation Message was successfully acquired; False to indicate that the
		/// Operation Message has been acquired before.
		/// </returns>
		public Boolean TryAcquire()
		{
			return Interlocked.Increment(ref mAcquireCount) == 1;
		}

		#endregion

		#region ++ Public Interface (Cancellation) ++

		/// <summary>
		/// Gets a reference to a cancellation token used to notify whether the operation should be canceled.
		/// </summary>
		/// 
		/// <exception cref="ObjectDisposedException">
		/// A method or property was called on an already disposed object.</exception>
		public CancellationToken CancellationToken
		{
			get
			{
				return mCancellationTokenSource.Token;
			}
		}


		/// <summary>
		/// Requests the cancellation of the operation.
		/// </summary>
		/// 
		/// <exception cref="ObjectDisposedException">
		/// A method or property was called on an already disposed object.</exception>
		/// <exception cref="AggregateException">
		/// An aggregate exception containing all the exceptions thrown by the registered callbacks on the 
		/// associated cancellation token.</exception>
		public void Cancel()
		{
			mCancellationTokenSource.Cancel();
		}

		#endregion

		#region ~~ Internal Interface ~~

		/// <summary>
		/// </summary>
		internal Operation()
		{
			_Initialize();
		}

		/// <summary>
		/// </summary>
		internal virtual void OnDispose()
		{
			if (mCancellationTokenSource != null)
				mCancellationTokenSource.Dispose();
		}

		#endregion

		#region Implementation

		[OnDeserialized]
		private void _OnDeserialized(StreamingContext context)
		{
			_Initialize();
		}

		private void _Initialize()
		{
			mCancellationTokenSource = new CancellationTokenSource();
		}

		#endregion

	}
}
